package com.yaser.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.yaser.dao.UserDao;
import com.yaser.model.User;
import com.yaser.service.AuthenticationService;
import com.yaser.util.exceptions.FreeBoxDaoException;
import com.yaser.util.exceptions.FreeBoxServiceException;

@Service("authenticationService")
public class AuthenticationServiceImpl implements AuthenticationService {

	
	@Resource(name = "authenticationManager")
	private AuthenticationManager authenticationManager; // specific for Spring
	// Security

	@Autowired
	private UserDao<User> userDao;

	@Override
	public User loginUser(String name, String password)
			throws FreeBoxServiceException {

		User user = null;
		try {
			user = userDao.findUser(name, password);
		} catch (FreeBoxDaoException e) {
			throw new FreeBoxServiceException(e);
		}

		return user;
	}


	@Override
	public boolean login(String username, String password) {
		try {
			Authentication authenticate = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(
							username, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(
						authenticate);
				return true;
			}
		} catch (AuthenticationException e) {
		}
		return false;
	}

	
	@Override
	public void logout() {
		SecurityContextHolder.getContext().setAuthentication(null);
		//currentUser.unauthenticate();
	}
}
